package com.yanchangapp.ui.activity.base;

import android.content.Intent;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.zxl.baselib.ui.base.BaseActivity;
import com.zxl.baselib.ui.base.BaseObserver;
import com.zxl.baselib.ui.base.BasePresenter;
import com.zxl.baselib.ui.base.ExceptionHandle;
import com.zxl.baselib.util.CheckUtils;
import com.zxl.baselib.util.Md5Utils;
import com.zxl.baselib.util.NetUtils;
import com.zxl.baselib.util.ui.ResHelper;
import com.zxl.baselib.util.ui.StatusBarHelper;
import com.zxl.baselib.util.ui.UIUtils;
import com.zxl.baselib.util.window.DisplayHelper;
import com.zxl.baselib.util.window.KeyboardHelper;
import com.yanchangapp.R;
import com.yanchangapp.base.ApiRetrofit;
import com.yanchangapp.commom.AppConstant;
import com.yanchangapp.model.cache.UserCache;
import com.yanchangapp.model.response.LoginResponse;
import com.yanchangapp.widget.VerificationSeekBar;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

import static com.yanchangapp.commom.AppConstant.REQUEST_SUCCESS;


/**
 * @author zxl on 2018/08/19.
 * discription:
 */
public class LoginActivity extends BaseActivity {
    @BindView(R.id.etAccount)
    EditText etAccount;
    @BindView(R.id.etPassword)
    EditText etPassword;
    @BindView(R.id.ivSeePwd)
    ImageView ivSeePwd;
    @BindView(R.id.btnLogin)
    Button btnLogin;
    @BindView(R.id.tvForget)
    TextView tvForget;
    @BindView(R.id.tvRegister)
    TextView tvRegister;
    @BindView(R.id.loginPage)
    View mLoginPage;
    @BindView(R.id.sb_progress)
    VerificationSeekBar mSeekBar;
    @BindView(R.id.tvDes)
    TextView mTvDes;
    private boolean isFirst = true;
    private int mButtonHeight;
    private ViewTreeObserver mTreeObserver;
    private ViewTreeObserver.OnGlobalLayoutListener mListener;
    private boolean mVertifyOk;
    private static final String TAG = "LoginActivity";
    private String account;
    private String password;

    @Override
    protected void init() {

    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_login;
    }

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        buttonBeyondKeyboardLayout(mLoginPage,tvRegister);
    }

    @Override
    protected void onDestroy() {
        if (mListener != null && mTreeObserver != null && mTreeObserver.isAlive()) {
            mTreeObserver.removeOnGlobalLayoutListener(mListener);
        }
        super.onDestroy();
    }


    @Override
    protected void initData() {

    }

    public void doLogin(){
        account = etAccount.getText().toString();
        password = etPassword.getText().toString();
        if (TextUtils.isEmpty(account)){
            UIUtils.showToast("账号不能为空");
            return;
        }

        if (TextUtils.isEmpty(password)){
            UIUtils.showToast("密码不能为空");
            return;
        }


        if (!CheckUtils.isPassword(password)){
            UIUtils.showToast("密码必须为6-16位数字或字母组合");
            return;
        }

        if (!mVertifyOk){
            UIUtils.showToast("请拖动滑块验证");
            return;
        }
        // 网络状况检查...
        if (!NetUtils.isConnectedAndToast(this)){
            return;
        }

        ApiRetrofit.getInstance().requestLogin(account, Md5Utils.md5(password))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<LoginResponse>() {
                    @Override
                    public void onNext(LoginResponse loginResponse ) {
                        if (loginResponse.getCode() == REQUEST_SUCCESS){
                            UserCache.putAccount(account);
                            UserCache.putPassword(password);
                            UserCache.putAuthorization(loginResponse.getAuthorization());
                            LoginResponse.UserBean user = loginResponse.getUser();
                            UserCache.putID(user.getId());
                            UserCache.putUsername(user.getUsername());
                            UserCache.putName(user.getName());
                            UserCache.putMobile(user.getMobile());
                            UserCache.putEmailDomain(user.getEmailDomain());
                            UserCache.putDepartmentName(user.getDepartmentName());
                            UserCache.putCompanyId(user.getCompanyId());
                            UserCache.putCompanyName(user.getCompanyName());
                            UserCache.putEmployeeId(user.getEmployeeId());
                            // web获取 手动设值...
                            UserCache.putPositionId(0);
                            UserCache.putDepartmentId(user.getDepartmentId());
                            if (user.getIdentity() != null){
                                UserCache.putIdentity(user.getIdentity().toString());
                            }
                            UserCache.putPositionName(user.getPositionName());
                            UserCache.putCompanyType(user.getCompanyType());
                            // 进行登录
                            jumpToMainActivity();
                        }else {
                            UIUtils.showToast(loginResponse.getMsg());
                        }
                    }

                    @Override
                    public void onError(ExceptionHandle.ResponseException exception) {

                    }
                });
    }

    public void jumpToMainActivity(){
        // 跳转页面并退出
        finish();
        jumpToActivity(MainActivity.class);
    }

    @Override
    protected void initListener() {
        mSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                if (seekBar.getProgress() != seekBar.getMax()) {
                    seekBar.setProgress(0);
                }else {
                    mVertifyOk = true;
                    mSeekBar.setEnabled(false);
                    mTvDes.setText("验证通过");
                    Drawable drawable = ResHelper.getDrawable(R.mipmap.slider_success);
                    mSeekBar.setThumb(drawable);
                    mSeekBar.setThumbOffset(drawable.getMinimumWidth());
                }
            }
        });
    }

    public  void actionChangeSee(){
        if (etPassword.getTransformationMethod() == HideReturnsTransformationMethod.getInstance()) {
            // 由可见变为不可见
            etPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
            ivSeePwd.setImageResource(R.mipmap.hide_pwd);
        } else {
            // 由不可见变为可见
            etPassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
            ivSeePwd.setImageResource(R.mipmap.show_pwd);
        }
    }


    @OnClick({R.id.ivSeePwd, R.id.btnLogin, R.id.tvForget, R.id.tvRegister,R.id.loginPage})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ivSeePwd:
                actionChangeSee();
                break;
            case R.id.btnLogin:
                doLogin();
                break;
            case R.id.tvForget:
                doJumpForget();
                break;
            case R.id.tvRegister:
                jumpToActivity(RegisterActivity.class);
                break;
            case R.id.loginPage:
                actionLoginPage();
                break;
        }
    }

    private void doJumpForget() {
        Intent intent = new Intent(this,ForgetPwdActivity.class);
        intent.putExtra(AppConstant.EXTRA_ORIFIN_LOGIN,AppConstant.EXTRA_ORIFIN_LOGIN);
        startActivity(intent);
    }

    // 点击了登录页
    public void actionLoginPage(){
        KeyboardHelper.hideKeyboard(mLoginPage);
    }

    private void buttonBeyondKeyboardLayout(final View root, final View button) {
        // 监听根布局的视图变化
        // 获取内容布局在窗体的可视区域
        // 获取内容布局在窗体的不可视区域高度(被其他View遮挡的区域高度)
        // top = 48 = 24*2 即为去除状态栏之外的区域
        // 若不可视区域高度大于100，则键盘显示
        // 获取须顶上去的控件在窗体的坐标
        // 计算root滚动高度，使scrollToView在可见区域
        /* scrollTo并未改变原来的位置
         *  貌似OnLayout可以
         * */// 键盘隐藏
        mListener = () -> {
            Rect rect = new Rect();
            // 获取内容布局在窗体的可视区域
            root.getWindowVisibleDisplayFrame(rect);
            // 获取内容布局在窗体的不可视区域高度(被其他View遮挡的区域高度)
            // top = 48 = 24*2 即为去除状态栏之外的区域
            int rootInvisibleHeight = root.getHeight() - rect.bottom;
            // 若不可视区域高度大于100，则键盘显示
            if (rootInvisibleHeight > 100) {
                int[] location = new int[2];
                // 获取须顶上去的控件在窗体的坐标
                button.getLocationInWindow(location);
                // 计算root滚动高度，使scrollToView在可见区域
                /* scrollTo并未改变原来的位置
                 *  貌似OnLayout可以
                 * */
                int buttonHeight = button.getHeight() + location[1];
                // 判断登录按钮是否包含在可是区域内
                if (rect.bottom > buttonHeight){
                    if (mListener != null && mTreeObserver.isAlive()) {
                        mTreeObserver.removeOnGlobalLayoutListener(mListener);
                    }
                    mListener = null;
                } else {
                    if (isFirst) {
                        mButtonHeight = (buttonHeight - rect.bottom + DisplayHelper.dp2Px(10));
                        isFirst = false;
                    }
                    root.scrollTo(0, mButtonHeight);
                }


            } else {
                // 键盘隐藏
                root.scrollTo(0, 0);
                isFirst = true;
            }
        };
        mTreeObserver = root.getViewTreeObserver();
        mTreeObserver.addOnGlobalLayoutListener(mListener);
    }
}
